package org.jeecg.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.modules.wms.entity.WmsMaterialWarningLog;
import org.jeecg.modules.wms.entity.WmsPurchaseArrivalInspection;
import org.jeecg.modules.wms.entity.WmsPurchaseOrder;
import org.jeecg.modules.wms.entity.WmsPurchaseOrderDetail;
import org.jeecg.modules.wms.mapper.WmsPurchaseOrderMapper;
import org.jeecg.modules.wms.service.IWmsMaterialWarningLogService;
import org.jeecg.modules.wms.service.IWmsPurchaseConfigService;
import org.jeecg.modules.wms.service.IWmsPurchaseOrderDetailService;
import org.jeecg.modules.wms.service.IWmsPurchaseOrderService;
import org.jeecg.modules.wms.vo.WmsMaterialWarningVO;
import org.jeecg.modules.wms.vo.WmsPurchaseOrderDetailVO;
import org.jeecg.modules.wms.vo.WmsPurchaseOrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.text.SimpleDateFormat;

import org.springframework.transaction.support.TransactionTemplate;
import org.jeecg.modules.wms.service.IWmsPurchaseArrivalInspectionService;

/**
 * @Description: 采购单主表Service实现类
 * @Author: jeecg-boot
 * @Date: 2023-07-17
 * @Version: V1.0
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class WmsPurchaseOrderServiceImpl extends ServiceImpl<WmsPurchaseOrderMapper, WmsPurchaseOrder> implements IWmsPurchaseOrderService {

    @Autowired
    private WmsPurchaseOrderMapper wmsPurchaseOrderMapper;

    @Autowired
    private IWmsPurchaseOrderDetailService wmsPurchaseOrderDetailService;

    @Autowired
    private IWmsMaterialWarningLogService wmsMaterialWarningLogService;

    @Autowired
    private IWmsPurchaseConfigService wmsPurchaseConfigService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private IWmsPurchaseArrivalInspectionService wmsPurchaseArrivalInspectionService;

    @Override
    public IPage<WmsPurchaseOrder> queryPurchaseOrderPageList(Page<WmsPurchaseOrder> page, Map<String, Object> queryParam) {
        // 确保按照创建时间倒序排序
        return wmsPurchaseOrderMapper.queryPurchaseOrderPageList(page, queryParam);
    }

    @Override
    public WmsPurchaseOrderVO getPurchaseOrderById(String id) {
        return wmsPurchaseOrderMapper.getPurchaseOrderById(id);
    }

    @Override
    @Transactional
    public Result<?> savePurchaseOrder(WmsPurchaseOrderVO purchaseOrderVO) {
        try {
            // 设置采购单基本信息
            WmsPurchaseOrder purchaseOrder = new WmsPurchaseOrder();
            BeanUtils.copyProperties(purchaseOrderVO, purchaseOrder);

            // 生成采购单号
            if (StringUtils.isBlank(purchaseOrder.getPurchaseNo())) {
                String purchaseNo = "CG" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 4);
                purchaseOrder.setPurchaseNo(purchaseNo);
            }

            // 设置状态为草稿
            purchaseOrder.setStatus(1);

            // 设置是否自动生成
            if (purchaseOrder.getIsAutoGenerated() == null) {
                purchaseOrder.setIsAutoGenerated(0);
            }

            // 保存采购单主表
            this.save(purchaseOrder);

            // 保存采购单明细
            List<WmsPurchaseOrderDetailVO> detailVOList = purchaseOrderVO.getDetailList();
            if (detailVOList != null && !detailVOList.isEmpty()) {
                List<WmsPurchaseOrderDetail> detailList = new ArrayList<>();

                // 将VO转换为实体类
                for (WmsPurchaseOrderDetailVO detailVO : detailVOList) {
                    WmsPurchaseOrderDetail detail = new WmsPurchaseOrderDetail();
                    BeanUtils.copyProperties(detailVO, detail);

                    // 设置采购单ID
                    detail.setPurchaseOrderId(purchaseOrder.getId());

                    // 计算金额
                    if (detail.getQuantity() != null && detail.getUnitPrice() != null) {
                        detail.setAmount(detail.getQuantity().multiply(detail.getUnitPrice()));
                    }

                    detailList.add(detail);
                }

                wmsPurchaseOrderDetailService.saveBatch(purchaseOrder.getId(), detailList);

                // 更新总金额
                updatePurchaseOrderTotalAmount(purchaseOrder.getId());
            }

            return Result.OK("保存成功", purchaseOrder.getId());
        } catch (Exception e) {
            log.error("保存采购单失败", e);
            return Result.error("保存失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<?> updatePurchaseOrder(WmsPurchaseOrderVO purchaseOrderVO) {
        try {
            // 获取原采购单信息
            WmsPurchaseOrder oldPurchaseOrder = this.getById(purchaseOrderVO.getId());
            if (oldPurchaseOrder == null) {
                return Result.error("采购单不存在");
            }

            // 只有草稿状态的采购单才能编辑
            if (oldPurchaseOrder.getStatus() != 1) {
                return Result.error("只有草稿状态的采购单才能编辑");
            }

            // 设置采购单基本信息
            WmsPurchaseOrder purchaseOrder = new WmsPurchaseOrder();
            BeanUtils.copyProperties(purchaseOrderVO, purchaseOrder);

            // 保留原有的不可编辑字段
            purchaseOrder.setPurchaseNo(oldPurchaseOrder.getPurchaseNo());
            purchaseOrder.setStatus(oldPurchaseOrder.getStatus());
            purchaseOrder.setIsAutoGenerated(oldPurchaseOrder.getIsAutoGenerated());
            purchaseOrder.setCreateBy(oldPurchaseOrder.getCreateBy());
            purchaseOrder.setCreateTime(oldPurchaseOrder.getCreateTime());

            // 更新采购单主表
            this.updateById(purchaseOrder);

            // 更新采购单明细
            List<WmsPurchaseOrderDetailVO> detailVOList = purchaseOrderVO.getDetailList();
            if (detailVOList != null) {
                List<WmsPurchaseOrderDetail> detailList = new ArrayList<>();

                // 将VO转换为实体类
                for (WmsPurchaseOrderDetailVO detailVO : detailVOList) {
                    WmsPurchaseOrderDetail detail = new WmsPurchaseOrderDetail();
                    BeanUtils.copyProperties(detailVO, detail);

                    // 设置采购单ID
                    detail.setPurchaseOrderId(purchaseOrder.getId());

                    // 计算金额
                    if (detail.getQuantity() != null && detail.getUnitPrice() != null) {
                        detail.setAmount(detail.getQuantity().multiply(detail.getUnitPrice()));
                    }

                    detailList.add(detail);
                }

                wmsPurchaseOrderDetailService.saveBatch(purchaseOrder.getId(), detailList);

                // 更新总金额
                updatePurchaseOrderTotalAmount(purchaseOrder.getId());
            }

            return Result.OK("更新成功");
        } catch (Exception e) {
            log.error("更新采购单失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<?> deletePurchaseOrder(String id) {
        try {
            // 获取采购单信息
            WmsPurchaseOrder purchaseOrder = this.getById(id);
            if (purchaseOrder == null) {
                return Result.error("采购单不存在");
            }

            // 只有草稿状态的采购单才能删除
            if (purchaseOrder.getStatus() != 1) {
                return Result.error("只有草稿状态的采购单才能删除");
            }

            // 删除采购单明细
            wmsPurchaseOrderDetailService.deleteByPurchaseOrderId(id);

            // 删除采购单主表
            this.removeById(id);

            return Result.OK("删除成功");
        } catch (Exception e) {
            log.error("删除采购单失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<?> batchDeletePurchaseOrder(List<String> ids) {
        try {
            int successCount = 0;
            int failCount = 0;

            for (String id : ids) {
                // 获取采购单信息
                WmsPurchaseOrder purchaseOrder = this.getById(id);
                if (purchaseOrder == null) {
                    failCount++;
                    continue;
                }

                // 只有草稿状态的采购单才能删除
                if (purchaseOrder.getStatus() != 1) {
                    failCount++;
                    continue;
                }

                // 删除采购单明细
                wmsPurchaseOrderDetailService.deleteByPurchaseOrderId(id);

                // 删除采购单主表
                this.removeById(id);

                successCount++;
            }

            if (failCount > 0) {
                return Result.OK("成功删除" + successCount + "条采购单，" + failCount + "条采购单不能删除（非草稿状态）");
            } else {
                return Result.OK("成功删除" + successCount + "条采购单");
            }
        } catch (Exception e) {
            log.error("批量删除采购单失败", e);
            return Result.error("批量删除失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<?> submitPurchaseOrder(String id) {
        try {
            // 获取采购单信息
            WmsPurchaseOrder purchaseOrder = this.getById(id);
            if (purchaseOrder == null) {
                return Result.error("采购单不存在");
            }

            // 只有草稿状态的采购单才能提交
            if (purchaseOrder.getStatus() != 1) {
                return Result.error("只有草稿状态的采购单才能提交");
            }

            // 检查是否有明细
            List<WmsPurchaseOrderDetail> detailList = wmsPurchaseOrderDetailService.selectByPurchaseOrderId(id);
            if (detailList == null || detailList.isEmpty()) {
                return Result.error("采购单没有明细，不能提交");
            }

            // 更新采购单状态为待审批
            updatePurchaseOrderStatus(id, 2);

            return Result.OK("提交成功");
        } catch (Exception e) {
            log.error("提交采购单失败", e);
            return Result.error("提交失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<?> approvePurchaseOrder(String id, Boolean approve, String remark) {
        try {
            // 获取采购单信息
            WmsPurchaseOrder purchaseOrder = this.getById(id);
            if (purchaseOrder == null) {
                return Result.error("采购单不存在");
            }

            // 只有待审批状态的采购单才能审批
            if (purchaseOrder.getStatus() != 2) {
                return Result.error("只有待审批状态的采购单才能审批");
            }

            // 更新采购单
            WmsPurchaseOrder updatePurchaseOrder = new WmsPurchaseOrder();
            updatePurchaseOrder.setId(id);
            updatePurchaseOrder.setUpdateTime(new Date());

            if (approve) {
                // 审批通过，更新状态为已审批
                updatePurchaseOrder.setStatus(3);
            } else {
                // 审批不通过，更新状态为草稿
                updatePurchaseOrder.setStatus(1);
            }

            // 更新备注
            if (StringUtils.isNotBlank(remark)) {
                updatePurchaseOrder.setRemark(remark);
            }

            this.updateById(updatePurchaseOrder);

            return Result.OK(approve ? "审批通过" : "审批不通过");
        } catch (Exception e) {
            log.error("审批采购单失败", e);
            return Result.error("审批失败: " + e.getMessage());
        }
    }

    // 重载方法，添加审核人和审核时间信息
    @Transactional
    public Result<?> approvePurchaseOrder(String id, Boolean approve, String remark, String approveBy, Date approveTime) {
        try {
            // 获取采购单信息
            WmsPurchaseOrder purchaseOrder = this.getById(id);
            if (purchaseOrder == null) {
                return Result.error("采购单不存在");
            }

            // 只有待审批状态的采购单才能审批
            if (purchaseOrder.getStatus() != 2) {
                return Result.error("只有待审批状态的采购单才能审批");
            }

            // 更新采购单
            WmsPurchaseOrder updatePurchaseOrder = new WmsPurchaseOrder();
            updatePurchaseOrder.setId(id);
            updatePurchaseOrder.setUpdateTime(new Date());

            if (approve) {
                // 审批通过，更新状态为已审批
                updatePurchaseOrder.setStatus(3);

                // 设置审核人和审核时间
                if (StringUtils.isNotBlank(approveBy)) {
                    updatePurchaseOrder.setApproveBy(approveBy);
                }

                if (approveTime != null) {
                    updatePurchaseOrder.setApproveTime(approveTime);
                } else {
                    updatePurchaseOrder.setApproveTime(new Date());
                }
            } else {
                // 审批不通过，更新状态为草稿
                updatePurchaseOrder.setStatus(1);
            }

            // 更新备注
            if (StringUtils.isNotBlank(remark)) {
                updatePurchaseOrder.setRemark(remark);
            }

            this.updateById(updatePurchaseOrder);

            return Result.OK(approve ? "审批通过" : "审批不通过");
        } catch (Exception e) {
            log.error("审批采购单失败", e);
            return Result.error("审批失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<?> cancelPurchaseOrder(String id) {
        try {
            // 获取采购单信息
            WmsPurchaseOrder purchaseOrder = this.getById(id);
            if (purchaseOrder == null) {
                return Result.error("采购单不存在");
            }

            // 已完成或已取消的采购单不能取消
            if (purchaseOrder.getStatus() == 5 || purchaseOrder.getStatus() == 6) {
                return Result.error("已完成或已取消的采购单不能取消");
            }

            // 更新采购单状态为已取消
            updatePurchaseOrderStatus(id, 6);

            return Result.OK("取消成功");
        } catch (Exception e) {
            log.error("取消采购单失败", e);
            return Result.error("取消失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<?> autoGeneratePurchaseOrder(List<String> warningIds) {
        try {
            if (warningIds == null || warningIds.isEmpty()) {
                return Result.error("未选择物料预警记录");
            }

            // 获取未处理的物料预警记录
            List<WmsMaterialWarningVO> warningList = new ArrayList<>();
            for (String id : warningIds) {
                WmsMaterialWarningLog warning = wmsMaterialWarningLogService.getById(id);
                if (warning != null && warning.getHandled() == 0 && warning.getWarningType() == 1) {
                    // 只处理未处理且低于下限的预警
                    WmsMaterialWarningVO warningVO = wmsMaterialWarningLogService.selectUnhandledWarnings().stream()
                            .filter(w -> w.getId().equals(id))
                            .findFirst()
                            .orElse(null);

                    if (warningVO != null) {
                        warningList.add(warningVO);
                    }
                }
            }

            if (warningList.isEmpty()) {
                return Result.error("所选预警记录已处理或不符合条件");
            }

            // 创建采购单
            WmsPurchaseOrderVO purchaseOrderVO = new WmsPurchaseOrderVO();

            // 设置采购单基本信息
            String purchaseNo = "PO" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 4);
            purchaseOrderVO.setPurchaseNo(purchaseNo);
            purchaseOrderVO.setStatus(1); // 草稿状态
            purchaseOrderVO.setIsAutoGenerated(1); // 自动生成

            // 如果预警记录中有相同的常用供应商，则设置为该供应商
            String commonSupplier = null;
            for (WmsMaterialWarningVO warning : warningList) {
                if (StringUtils.isNotBlank(warning.getCommonSupplier())) {
                    if (commonSupplier == null) {
                        commonSupplier = warning.getCommonSupplier();
                    } else if (!commonSupplier.equals(warning.getCommonSupplier())) {
                        commonSupplier = null;
                        break;
                    }
                }
            }

            if (StringUtils.isNotBlank(commonSupplier)) {
                purchaseOrderVO.setSupplier(commonSupplier);
            }

            // 设置预计到货日期为7天后
            Date expectedArrivalDate = new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000L);
            purchaseOrderVO.setExpectedArrivalDate(expectedArrivalDate);

            // 创建采购单明细
            List<WmsPurchaseOrderDetailVO> detailVOList = new ArrayList<>();
            for (WmsMaterialWarningVO warning : warningList) {
                WmsPurchaseOrderDetailVO detailVO = new WmsPurchaseOrderDetailVO();
                detailVO.setMaterialCode(warning.getMaterialCode());
                detailVO.setMaterialName(warning.getMaterialName());
                detailVO.setMaterialType(warning.getMaterialType());
                detailVO.setSpecification(warning.getSpecification());
                detailVO.setUnit(warning.getUnit());

                // 建议采购量 = 预警上限 - 当前库存量
                BigDecimal suggestedQuantity = warning.getUpperLimit().subtract(warning.getCurrentQuantity());
                detailVO.setQuantity(suggestedQuantity);

                // 如果有最近采购价格，则设置为该价格
                if (warning.getLastPurchasePrice() != null) {
                    detailVO.setUnitPrice(warning.getLastPurchasePrice());
                    detailVO.setAmount(suggestedQuantity.multiply(warning.getLastPurchasePrice()));
                }

                detailVOList.add(detailVO);
            }

            purchaseOrderVO.setDetailList(detailVOList);

            // 保存采购单
            Result<?> saveResult = savePurchaseOrder(purchaseOrderVO);
            if (!saveResult.isSuccess()) {
                return saveResult;
            }

            // 获取保存后的采购单ID
            String purchaseOrderId = (String) saveResult.getResult();

            // 关联预警记录和采购单
            for (String id : warningIds) {
                wmsMaterialWarningLogService.updatePurchaseOrderId(id, purchaseOrderId);
            }

            return Result.OK("生成采购单成功", purchaseOrderId);
        } catch (Exception e) {
            log.error("自动生成采购单失败", e);
            return Result.error("生成采购单失败: " + e.getMessage());
        }
    }

    @Override
    public boolean updatePurchaseOrderStatus(String id, Integer status) {
        return wmsPurchaseOrderMapper.updatePurchaseOrderStatus(id, status) > 0;
    }

    @Override
    public boolean updatePurchaseOrderTotalAmount(String id) {
        return wmsPurchaseOrderMapper.updatePurchaseOrderTotalAmount(id) > 0;
    }

    @Override
    public Result<?> saveOrder(WmsPurchaseOrderVO purchaseOrderVO) {
        // 设置采购单基本信息
        WmsPurchaseOrder purchaseOrder = new WmsPurchaseOrder();
        // 复制属性
        BeanUtils.copyProperties(purchaseOrderVO, purchaseOrder);
        purchaseOrder.setStatus(1); // 设置状态为草稿
        purchaseOrder.setIsCompleted(0); // 设置为未执行完成
        // 生成采购单号
        if (StringUtils.isBlank(purchaseOrder.getPurchaseNo())) {
            String purchaseNo = "CG" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 4);
            purchaseOrder.setPurchaseNo(purchaseNo);
        }

        // 设置是否自动生成
        if (purchaseOrder.getIsAutoGenerated() == null) {
            purchaseOrder.setIsAutoGenerated(0);
        }

        // 保存采购单主表
        this.save(purchaseOrder);

        // 保存采购单明细
        List<WmsPurchaseOrderDetailVO> detailVOList = purchaseOrderVO.getDetailList();
        if (detailVOList != null && !detailVOList.isEmpty()) {
            List<WmsPurchaseOrderDetail> detailList = new ArrayList<>();

            // 将VO转换为实体类
            for (WmsPurchaseOrderDetailVO detailVO : detailVOList) {
                WmsPurchaseOrderDetail detail = new WmsPurchaseOrderDetail();
                BeanUtils.copyProperties(detailVO, detail);

                // 设置采购单ID
                detail.setPurchaseOrderId(purchaseOrder.getId());

                // 计算金额
                if (detail.getQuantity() != null && detail.getUnitPrice() != null) {
                    detail.setAmount(detail.getQuantity().multiply(detail.getUnitPrice()));
                }
                detail.setMaterialId(detailVO.getMaterialId());
                detailList.add(detail);
            }

            wmsPurchaseOrderDetailService.saveBatch(purchaseOrder.getId(), detailList);

            // 更新总金额
            updatePurchaseOrderTotalAmount(purchaseOrder.getId());
        }

        return Result.OK("保存成功", purchaseOrder.getId());
    }

    @Override
    public Result<?> updateOrder(WmsPurchaseOrderVO purchaseOrderVO) {
        // 调用已存在的方法
        return updatePurchaseOrder(purchaseOrderVO);
    }

    @Override
    public Result<?> deleteOrder(String id) {
        // 调用已存在的方法
        return deletePurchaseOrder(id);
    }

    @Override
    public Result<?> deleteOrders(List<String> ids) {
        // 调用已存在的方法
        return batchDeletePurchaseOrder(ids);
    }

    @Override
    public Result<?> submitOrder(String id) {
        // 调用已存在的方法
        return submitPurchaseOrder(id);
    }

    @Override
    public Result<?> approveOrder(String id, Integer approveStatus, String remark, Map<String, Object> params) {
        // 获取审核人和审核时间
        String approveBy = null;
        Date approveTime = null;

        if (params != null) {
            if (params.get("approveBy") != null) {
                approveBy = params.get("approveBy").toString();
            }

            if (params.get("approveTime") != null) {
                if (params.get("approveTime") instanceof Date) {
                    approveTime = (Date) params.get("approveTime");
                } else {
                    try {
                        approveTime = new Date(Long.parseLong(params.get("approveTime").toString()));
                    } catch (Exception e) {
                        approveTime = new Date();
                    }
                }
            }
        }

        // 调用重载方法，传递审核人和审核时间
        boolean approve = (approveStatus == 1);
        return approvePurchaseOrder(id, approve, remark, approveBy, approveTime);
    }

    @Override
    public Result<?> cancelOrder(String id) {
        // 调用已存在的方法
        return cancelPurchaseOrder(id);
    }

    @Override
    @Transactional
    public Result<?> generatePurchaseOrderFromWarnings(List<String> warningIds, String supplier) {
        try {
            if (warningIds == null || warningIds.isEmpty()) {
                return Result.error("请选择需要处理的预警记录");
            }

            // 查询物料预警记录
            List<WmsMaterialWarningVO> warningList = wmsMaterialWarningLogService.selectWarningsByIds(warningIds);
            if (warningList == null || warningList.isEmpty()) {
                return Result.error("未找到相关预警记录");
            }

            // 创建采购单
            WmsPurchaseOrder purchaseOrder = new WmsPurchaseOrder();
            String purchaseNo = "CG" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 4);
            purchaseOrder.setPurchaseNo(purchaseNo);
            purchaseOrder.setSupplier(supplier);
            purchaseOrder.setStatus(1); // 草稿状态
            purchaseOrder.setIsAutoGenerated(1); // 自动生成

            // 从Spring Security上下文获取当前用户
            String username = null;
            try {
                org.apache.shiro.subject.Subject subject = org.apache.shiro.SecurityUtils.getSubject();
                if (subject != null && subject.getPrincipal() != null) {
                    org.jeecg.common.system.vo.LoginUser loginUser = (org.jeecg.common.system.vo.LoginUser) subject.getPrincipal();
                    username = loginUser.getUsername();
                }
            } catch (Exception e) {
                username = "system";
            }

            purchaseOrder.setCreateBy(username != null ? username : "system");
            purchaseOrder.setCreateTime(new Date());

            // 保存采购单主表
            this.save(purchaseOrder);

            // 创建采购单明细
            List<WmsPurchaseOrderDetail> detailList = new ArrayList<>();
            for (WmsMaterialWarningVO warning : warningList) {
                WmsPurchaseOrderDetail detail = new WmsPurchaseOrderDetail();
                detail.setPurchaseOrderId(purchaseOrder.getId());
                detail.setMaterialCode(warning.getMaterialCode());
                detail.setMaterialName(warning.getMaterialName());
                detail.setMaterialType(warning.getMaterialType());
                detail.setSpecification(warning.getSpecification());
                detail.setUnit(warning.getUnit());

                // 计算采购数量 = 预警上限 - 当前库存
                BigDecimal currentStock = warning.getCurrentQuantity() != null ? warning.getCurrentQuantity() : BigDecimal.ZERO;
                BigDecimal warningUpper = warning.getUpperLimit() != null ? warning.getUpperLimit() : BigDecimal.valueOf(100);
                BigDecimal quantity = warningUpper.subtract(currentStock);
                if (quantity.compareTo(BigDecimal.ZERO) <= 0) {
                    quantity = BigDecimal.valueOf(10); // 默认采购10个
                }
                detail.setQuantity(quantity);

                // 获取最近采购单价
                List<WmsPurchaseOrderDetail> historicalDetails = wmsPurchaseOrderDetailService.selectLatestByMaterialCode(warning.getMaterialCode(), 1);
                if (historicalDetails != null && !historicalDetails.isEmpty() && historicalDetails.get(0).getUnitPrice() != null) {
                    detail.setUnitPrice(historicalDetails.get(0).getUnitPrice());
                } else {
                    detail.setUnitPrice(BigDecimal.ZERO);
                }

                // 计算金额
                detail.setAmount(detail.getQuantity().multiply(detail.getUnitPrice()));
                detail.setReceivedQuantity(BigDecimal.ZERO);

                detailList.add(detail);
            }

            // 保存明细
            wmsPurchaseOrderDetailService.saveBatch(detailList);

            // 更新总金额
            updatePurchaseOrderTotalAmount(purchaseOrder.getId());

            return Result.OK("生成采购单成功", purchaseOrder.getId());
        } catch (Exception e) {
            log.error("从预警生成采购单失败", e);
            return Result.error("生成采购单失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> saveArrivalInfo(String purchaseOrderId, String arrivalDate, List<Map<String, Object>> details, List<Map<String, Object>> unqualifiedList, String username) {
        // 查询采购单信息
        WmsPurchaseOrder purchaseOrder = this.getById(purchaseOrderId);
        if (purchaseOrder == null) {
            return Result.error("采购单不存在");
        }

        if (purchaseOrder.getStatus() != 3 && purchaseOrder.getStatus() != 7 && purchaseOrder.getStatus() != 8) {
            return Result.error("只有已审批、已到货或部分到货的采购单才能进行到货操作");
        }
        try {
            // 1. 保存质检结果 - 不再删除旧数据，而是创建新记录
            int savedCount = wmsPurchaseArrivalInspectionService.batchSave(
                    purchaseOrderId,
                    purchaseOrder.getPurchaseNo(),
                    arrivalDate,
                    details,
                    username
            );
            log.info("保存合格质检记录：" + savedCount + "条");

            // 2. 保存不合格质检结果 - 同样创建新记录
            int unqualifiedCount = 0;
            if (unqualifiedList != null && !unqualifiedList.isEmpty()) {
                unqualifiedCount = wmsPurchaseArrivalInspectionService.batchSaveUnqualified(
                        purchaseOrderId,
                        purchaseOrder.getPurchaseNo(),
                        arrivalDate,
                        unqualifiedList,
                        username
                );
                log.info("保存不合格质检记录：" + unqualifiedCount + "条");
            }

            // 3. 更新采购单状态
            // 统计是否所有物料都已到货
            boolean allArrived = true;

            // 获取采购单明细
            List<WmsPurchaseOrderDetail> orderDetails = wmsPurchaseOrderDetailService.queryDetailList(purchaseOrderId);


            //根据采购单编号获取所有质检结果
            List<WmsPurchaseArrivalInspection> list = wmsPurchaseArrivalInspectionService.list(new QueryWrapper<WmsPurchaseArrivalInspection>()
                    .eq("purchase_order_id", purchaseOrderId));

            // 创建物料到货数量映射
            Map<String, BigDecimal> arrivalQuantityMap = list.stream()
                    .collect(Collectors.toMap(
                            detail -> detail.getMaterialId(),
                            detail -> detail.getArrivalQuantity(),
                            BigDecimal::add // 如果有重复的key，则累加值
                    ));

            // 检查是否所有物料都已到货
            for (WmsPurchaseOrderDetail orderDetail : orderDetails) {
                BigDecimal arrivalQuantity = arrivalQuantityMap.getOrDefault(orderDetail.getMaterialId(), BigDecimal.ZERO);
                if (arrivalQuantity.compareTo(orderDetail.getQuantity()) < 0) {
                    allArrived = false;
                    break;
                }
            }

            // 更新采购单状态
            purchaseOrder.setStatus(allArrived ? 7 : 8); // 7-已到货，8-部分到货

            // 4. 检查是否有历史不合格记录
            Long historyUnqualifiedCount = wmsPurchaseArrivalInspectionService.count
                    (
                            new QueryWrapper<WmsPurchaseArrivalInspection>()
                                    .eq("purchase_order_id", purchaseOrderId)
                                    .eq("inspection_result", 0) // 不合格
                    );

            // 设置退换货状态
            if ((unqualifiedList == null || unqualifiedList.isEmpty()) && historyUnqualifiedCount == 0) {
                // 没有不合格数据且历史上也没有不合格记录，设置为无需退换货
                purchaseOrder.setReturnExchangeStatus(0);
            } else {
                // 有不合格数据或历史上有不合格记录，设置为等待处理
                purchaseOrder.setReturnExchangeStatus(1);
            }

            purchaseOrder.setUpdateBy(username);
            purchaseOrder.setUpdateTime(new Date());
            this.updateById(purchaseOrder);

            return Result.OK("保存成功");
        } catch (Exception e) {
            log.error("保存采购到货信息失败", e);
            return Result.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 更新采购单状态（已到货/部分到货）
     *
     * @param purchaseOrderId 采购单ID
     */
    public void updatePurchaseOrderStatus(String purchaseOrderId) {
        try {
            // 1. 查询采购单信息
            WmsPurchaseOrder purchaseOrder = this.getById(purchaseOrderId);
            if (purchaseOrder == null) {
                log.error("采购单不存在: {}", purchaseOrderId);
                return;
            }

            // 2. 查询采购单明细，获取总采购数量
            List<WmsPurchaseOrderDetail> detailList = wmsPurchaseOrderDetailService.list(
                    new QueryWrapper<WmsPurchaseOrderDetail>()
                            .eq("purchase_order_id", purchaseOrderId)
            );

            Map<String, BigDecimal> totalQuantityMap = new HashMap<>();
            for (WmsPurchaseOrderDetail detail : detailList) {
                totalQuantityMap.put(detail.getMaterialId(), detail.getQuantity());
            }

            // 3. 查询所有到货记录（包括合格和不合格）
            List<WmsPurchaseArrivalInspection> inspectionList = wmsPurchaseArrivalInspectionService.list(
                    new QueryWrapper<WmsPurchaseArrivalInspection>()
                            .eq("purchase_order_id", purchaseOrderId)
            );

            // 4. 计算每个物料的到货数量（合格 + 不合格）
            Map<String, BigDecimal> arrivalQuantityMap = new HashMap<>();
            for (WmsPurchaseArrivalInspection inspection : inspectionList) {
                String materialId = inspection.getMaterialId();
                BigDecimal arrivalQuantity = inspection.getArrivalQuantity() != null ?
                        inspection.getArrivalQuantity() : BigDecimal.ZERO;

                // 累加同一物料的到货数量
                BigDecimal currentTotal = arrivalQuantityMap.getOrDefault(materialId, BigDecimal.ZERO);
                arrivalQuantityMap.put(materialId, currentTotal.add(arrivalQuantity));
            }

            // 5. 判断是否全部到货
            boolean isFullyArrived = true;
            for (Map.Entry<String, BigDecimal> entry : totalQuantityMap.entrySet()) {
                String materialId = entry.getKey();
                BigDecimal totalQuantity = entry.getValue();
                BigDecimal arrivalQuantity = arrivalQuantityMap.getOrDefault(materialId, BigDecimal.ZERO);

                // 如果有任何一个物料的到货数量小于采购数量，则为部分到货
                if (arrivalQuantity.compareTo(totalQuantity) < 0) {
                    isFullyArrived = false;
                    break;
                }
            }

            // 6. 更新采购单状态
            Integer newStatus = isFullyArrived ? 7 : 8; // 7: 已到货, 8: 部分到货

            // 只有当状态需要变更时才更新
            if (!newStatus.equals(purchaseOrder.getStatus())) {
                this.update(
                        new WmsPurchaseOrder().setStatus(newStatus),
                        new QueryWrapper<WmsPurchaseOrder>().eq("id", purchaseOrderId)
                );
                log.info("更新采购单状态: {} -> {}", purchaseOrder.getStatus(), newStatus);
            }
        } catch (Exception e) {
            log.error("更新采购单状态失败", e);
        }
    }
} 